package sms.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import sms.entity.User;
import sms.service.UserService;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public User login(String username, String password) {
        String sql="select * from user where username=? and password=?";

        try {
            return jdbcTemplate.queryForObject(sql, (rs, rowNum) -> {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setRole(rs.getString("role"));

                return user;
            }, username, password);
        } catch (EmptyResultDataAccessException e) {
            return null;  // 找不到用户返回null
        }
    }

    @Override
    public void addUser(User user) {
        String sql="insert into user(username,password,role) values(?,?,?)";
        jdbcTemplate.update(sql,user.getUsername(),user.getPassword(),user.getRole());
    }

    @Override
    public User getUser(int id) {
        String sql="select * from user where id=?";
        return jdbcTemplate.queryForObject(sql,(rs, rowNum) -> {
            User user = new User();
            user.setId(rs.getInt("id"));
            user.setUsername(rs.getString("username"));
            user.setPassword(rs.getString("password"));
            user.setRole(rs.getString("role"));

            return user;
        },id);
    }
}